- Special Edition Using Visual Basic Script -

Chapter 12 - A Simple VBScript Page

by Ron Schwarz


In this chapter

When you complete this chapter, you'll have a good grasp of what VBS is, and how to use it. You'll have the foundation required to grasp the information provided in the rest of this book. At that point, you should have a "feel" for VBS, and be able to rapidly pick up the more weighty information that follows.

Although you will create some working VBS pages in this chapter, you will not find HTML covered to any great extent. HTML is covered in greater depth in Chapter 2, "Review of HTML." This chapter is a full-immersion in VBS, and VBS alone.

Coming Up to Speed with Visual Basic

If you're familiar with Visual Basic, you may want to skip ahead to the next section, "Identifying the Important Differences Between VB and VBScript." If, however, You're new to VB, take a moment here to bone up on VB essentials. This short primer will help you understand a few important VB principles.

Visual Basic is a programming language that features a visual IDE (Integrated Development Environment) which is used to create Windows applications. In VB, you create "Forms," which contain "Controls," and associated code. A VB Form is a window. (A VB form is related in name only to an HTML form.)

When you write a VB program, you begin by placing controls, such as Labels, TextBoxes, and Command Buttons on a Form. Form creation is interactive, and very easy. You select controls from a toolbox, and place them on the form. You use the mouse to position and size them, and set their properties from the Properties window, which is a list of properties and values.

After you create an object (a form or a control) you set its Properties, and enter event code, and non-event program code. (Simply double-clicking a form or control will bring up the editor, with the cursor positioned in an automatically created procedure skeleton for the selected object.)

At this point, it might be good to remind yourself that we're discussing VB, and not VBS. The reason for this will become apparent when we begin to discuss VBS.

Properties, Events, and Methods

In Visual Basic, most objects (such as Forms and Controls) have three key features: Properties, Events, and Methods. A Property controls a characteristic, such as size, color, contents, or position. Events are things that occur while the program is running. Examples are mouse clicks, keystrokes, and form resizing. Event Procedures are blocks of code that are automatically executed when the associated event happens. For example, when the mouse is clicked over a form named Form1, the Form1_Click procedure will be executed.

You can also have Sub procedures and Functions that are not associated with events. These routines must be accessed by other codeùthey will not execute automatically.

Methods are instructions to objects. When you invoke a method, you are telling the object to execute a specific set of instructions. Examples of Methods are Print, Refresh, Show, and Hide.

These principles all carry over to VBS, even though their actual implementation is quite different.

Visual Basic code is located in either the General or Events sections of a Form. (Code Modules are similar to Forms, but contain only a General section, and have no visual interface.)

The General section consists of two parts. The first part is the Declarations section, which contains non-executable code, such as variable and API call declarations. The rest of the General section contains procedures that are not attached to events. An example of a procedure in the General section would be a routine that centers your form on the screen. Such a procedure could be called from anywhere, and is not directly attached to any one specific event.

The Events section of a Form contains Sub procedures that are connected to events. When you click a Command Button, for example, any code in its Click event (such as Command1_Click) will execute.

Identifying the Important Differences Between VB and VBScript

There are three main areas in which VBS differs from VB. These are the development environment, the instruction set, and the user interface.

At this time, it might be good to point out that VBS is not a new version of VB, nor is it a general purpose programming language. While you may be able to port certain routines from a VB app to a VBS script, you will not generally be able to port most entire applications to VBS, barring superhuman effort far beyond the point at which the law of diminishing returns has been invoked.

VBS is designed to make Web pages interactive and intelligent. By leveraging your VB skills, you'll be able to get up to speed quickly. Although you may have to make a conscious effort to remember that a VBS-enabled Web page is not a VB application, you'll find that the possibilities, especially when using VBS in conjunction with the powerful new HTML Layout features, to be endless.

Development Environment

When Microsoft first announced VBScript, it had no IDE. All coding, control creation and placementùeverythingùhad to be done in code, and all code had to be created with an ASCII text editor, such as Notepad. Now, the ActiveX Control Pad makes creation and maintenance of VBS pages nearly painless. Like "real" VB, VBS pages can be designed interactively and visually. The IDE provided with the ActiveX Control Pad is very similar to the one in VB, and you'll have no problem transitioning to it if you're at all familiar with VB.

Still, there are differences. Perhaps the most notable are the lack of a Run Mode, and the lack of a Debugger. (Remember, you're not creating programs, per se, but Web pages, and the "run environment" of a Web page is a Web browserùso, the final product of your efforts, for all its amazing power and flexibility, is not a program in the literal sense; it requires a specialized environment (such as the Internet Explorer), in order to run.)

In HTML, you're working with a document, rather than a VB-style "form." The browser receives the page as a stream of data, and formats it as it displays it. If you change the width of the browser window, in most cases, you'll also be reformatting the contents of the page.

As a result of this inherent difference from the VB form model, on-screen control placement is essentially determined by control declaration context. Where you "create" your controls determines where they will be placed in the document when it's displayed.

As limiting and restrictive as this sounds, you can do quite a bit by carefully constructing your HTML and using advanced features, such as frames. When you are script-enabling existing HTML pages, this is probably what you'll find yourself doing most of the time. However, when creating new pages, you will be wise to consider doing most, if not all of your development within HTML Layout Style Pages.

HTML Layout Style Pages provide a very close approximation of the Visual Basic Form modelùyou can place, position, and size ActiveX controls on a page anywhere you choose, without any regard for HTML stream-of-text issues. And, you can set properties by using a Properties window, just like you can in VB. Finally, you can use a powerful Script Wizard to manage event code and method insertion.

Instruction Set

VBS is a subset of the Visual Basic language. Many statements, features, and functions you may be accustomed to using in VB are not available. Some are missing due to security considerations (you wouldn't want to have critical files on your local machine corrupted or deleted simply by clicking a link on a Web page, for instance), and others are unimplemented to keep the "footprint" small. You can work around some of the differences (for example, you can use the ElseIf keyword to compensate for the lack of a Select Case structure, and you can use multiple arrays instead of using typed record variables), but others may very well present impenetrable barriers. There is, for example, no direct file I/O available. This means you won't be able to use any sequential, binary, or random file I/O in your scripts. The specific differences in instruction sets are covered in greater detail in later chapters. For now, be aware that there are differences, many of which are non-trivial.

User Interface

VBS provides a high degree of flexibility and functionality. However, unless you are using HTML Layout Style Pages, it is important to keep in mind the fact that the underlying container is still an HTML Web page, and is not a VB form. Much of the "look and feel" of a VBS-enabled page is determined by (and, limited by) HTML factors. Elements such as toolbars, menus, MDI forms, multiple windows, and standard graphics methods are for the time being beyond the province of VBS scripting. (However, it is possible to implement many of these features by using ActiveX controlsùby keeping a watchful eye on the market, you will quite likely to find controls appropriate to the task at hand, as new ones are constantly being developed and released.)

As HTML Layout Style Pages become more of a standard, you can expect demand for (and proficiency in) "traditional" HTML pages to rapidly diminish. Still, it's good to learn as much as you can, because they will be with us in one form or another for some time, even as they are superseded by the newer standard.

Users who have used a variety of Windows apps, and are familiar with existing Web browsers, will have little difficulty making the transition to VBS-enabled pages. Users who are new to Web browsers, and users whose exposure to Windows apps is limited to Web browsers (of which there are quite a few) can expect to experience a bit of a learning curve. This will be ameliorated by virtue of the ease of use these pages provide.

Creating a VBS-Enabled Page

A VBS-enabled page consists of a mix of HTML blocks and/or HTML Layout declarations, Control declarations, and VBS scripts. (Strictly speaking, Control and Script blocks are also HTML, but we are now examining the differences between HTML code and VBS code.) HTML is a fairly crude language (it is essentially a top-down text formatter), and one advantage you have over a "pure" HTML programmer is the fact that much of the HTML functionality can be done more simply in VBS. Still, you'll need to learn some HTML basics, and this section will give you what you need to get started. HTML itself is be covered in greater detail in Chapter 2, "Review of HTML."

HTML Syntax and Statements

If you've used WordPerfect in the past, you're probably already familiar with the most noticeable characteristic of HTML tagsùpaired commands. Most HTML commands are used in pairs. For instance, if you wanted to center a line of text, you'd precede it with a <Center> command (or "tag") and place a </Center> command at the end. (The "/" in the second command designates it as the closing half of a command pair.) Everything inside the block is centered, even if it requires multiple lines of text.

Because HTML is designed to be formatted on-the-fly by the browser, whitespace generally is meaningless. Carriage returns, tabs, and spaces are "eaten" by the browser, in the absence of specific formatting commands. (This affects control, as well as text placement.) Therefore this block:

<Center>Simple HTML Command Demo</Center>

is functionally identical to this block:

<Center>

Simple HTML

Command

Demo

</Center>

Next, we'll examine a few HTML statements.

<HTML>

The <HTML> statement is used at the beginning and end (as </HTML>) of a page. It tells the browser that everything in the resultant block is HTML code and text.

<Head>

The <Head></Head> section exists primarily for purposes of source code organization. As a rule, you should place non-displayed parts of your HTML page in the <Head> section. This includes VBS scripts, but not control declarations.

<Body>

The <Body></Body> block is the counterpart to the <Head></Head> block. Place your displaying elements here, such as text, links, and controls.

<Title>

The <Title></Title> block defines a block of text, which is placed in the title bar of the browser. It is similar to a VB form's Caption property.

<Hn>

The <Hn></Hn> block defines a text style used for headers. <H1> is the largest, <H2> is the next smallest, and so on. (<H6> is the smallest.)

<Script...>

<Script...> and </Script> tags are used to mark off your VBS scripts. Their use is discussed further on in this chapter in the section labeled "Script Blocks."

<Input...>

The <Input...> tag is used to declare HTML controls. Its usage is explained later on in this chapter in the section labeled "Buttons."

<Object...>

The <Object...></Object> pair is used to declare ActiveX controls, and is described later on in this chapter in the "Declaring the Controls" section.

<!...>

Prefacing any HTML tag with a "!" changes it into a comment, similar to Rem or [sp] in VB.

<!-- ... -->

You can mark several lines with the Extended Comment tags. These are open-ended (no closing ">") at the start, and close-ended at the end. All lines in between will be converted to comments, if your browser cannot execute them. This can be used to hide your <Script> blocks from displaying as text on browsers that cannot execute them. They will still not execute, but, they will at least not show up on the users' screens.

<! This is a single line comment >
<!-- And so is this -- >
<! This is an extended (multi-line) comment. Some browsers improperly
interpret comments that span more than one line, so this form should
be avoided. >

<A HREF=...></A>

The <A> (Anchor) tag is generally used to designate a link to another URL. The format is:

<A HREF="http://url.address"></A>

<P>

<P> is the Paragraph command. When you want to insert a carriage return in the flow of text (which also determines control placement), insert a <P> command. This command is different from most HTML statements in that it is not part of a command pair. There is no closing </P> statement, because <P> does not create a block; it merely inserts a line break wherever it appears.

<Center>

<Center> and </Center> create a block of centered text. All text between them is centered. Placing <P> paragraph markers inside a centered block will insert line breaks, but will not turn off centering. The same applies for other HTML formatting command pairs, which are covered in more detail in other chapters.

Control Declarations

As discussed earlier, there is no visual "drag and drop" means for placing controls on Web pages when using VBS. Instead, controls are embedded in pages by means of declaration statement blocks. There are two types of controls: HTML controls, and ActiveX controls. Each type is declared using its own syntax, which we will examine in this section.

HTML Intrinsic Controls

HTML has a number of built-in controls, including equivalents to the Command Button, OptionButton, CheckBox, ComboBox, and TextBox that are used in VB programming.

Although they offer similar functionality, there are differences in usage.

ActiveX Controls

ActiveX is the name that Microsoft has given to 32-bit custom controls contained in .OCX files. They are the successors to the venerable .VBX controls, which were designed for earlier (16-bit) versions of Visual Basic.

A wide selection of ActiveX controls are available, providing nearly limitless potential. We'll examine two (Label and Timer) that are primarily intended for use with the Internet Explorer. Once you learn the techniques involved in embedding them in HTML, you'll be able to make use of others as the need arises.

Script Blocks

All VBS code is contained in Script blocks. These are HTML blocks beginning with <Script> (see following code segment), and ending with </Script>. You can have more than one block, however, at least the first one must specify VBS as the language you're using, as in:

The LANGUAGE= clause tells the browser that this script contains VBScript code (as opposed to another scripting language, such as JavaScript). Following scripts on the same page can simply begin with <Script>. The <Script> tag has other options; we'll examine some of them later on.

Code contained in a VBS script falls into one of three categories: initialization code, event code, and non-event code.

Initialization Code

Initialization code is code that executes when the Web page loads, without requiring any action on the user's part. If you're familiar with VB, you're familiar with the Form_Load event, which executes when a form is loaded into memory, and the Sub Main procedure, which will execute automatically when a program is loaded (if the project has the "Use Sub Main" option selected). VBS initialization code is similar; however, it actually hearkens back to pre-VB days. Earlier versions of BASIC, such as QuickBasic and PDS 7.x were (like VBS) non-window-oriented languages. Although they had Sub procedures and Functions (like VB), they also had the ability to place executable code outside of any named procedures. In VB, only non-executable code, such as variable and API declarations, can be placed outside of named procedures.

VBS will allow you to place executable code there; however, there are a few caveats, and doing so is not encouraged unless you have a specific reason, and are prepared for some extra work. You may find, for instance, that when you set properties of ActiveX controls in your initialization code, not all of them are in fact assigned, yet no errors are generated.

Event Code

Just as in "regular" VB, objects used with VBS can generate events. And, like VB, event code will automatically execute when the associated events occur.

The ActiveX Control Pad can, like the regular VB IDE, create event headers for you.

Non-Event Procedures

In addition to writing procedures that execute automatically when objects generate events, you can also create procedures that can only be invoked by code. The format is the same as that used with event procedures, with the following exceptions: you can create Functions, as well as Sub procedures (Functions return a value in their name, and are invoked on the right side of the equal sign), and, you can declare your own parameter lists.

Before you can create your first page, you will need to an understanding of data types, and controls. The next two sections cover this material.

Introducing Data Types

VB has a variety of data types, including user-defined typed structures. VBS, however, has only one data type: the Variant. Fortunately, a variable of Variant type can contain nearly any type of data, and treat it as a subtype. So, you can store strings, numeric values, dates, and so forth. You can use the VarType function to determine what subtype is in use in a particular variable, and, there are several conversion functions built into VBS, which make it possible to convert data from one subtype to another. These features are described more fully in Chapter 16, "VBScript Data Types, Variables, and Structures."

A short summary of several common data types follows:

Type Description

Boolean Either returns True or False

Byte Unsigned Integer limited to a range of 0 û 255

Integer Signed integer, range is û32,768 û 32,767

Single Single-precision floating-point subtype; can hold negative values from û3.402823E38 to û1.401298E-45, and positive values from 1.401298E-45 to 3.402823E38.

Double Double-precision floating point subtype; can hold very large (or small) values

Date Value contains a numeric representation of a date

String Can hold a string up to about 2 billion characters; fixed-length strings are not supported

Introducing Controls and Events

Now that we've had an overview of controls and events, let's dig in, and actually create some pages that use them. We'll begin with a simple page that demonstrates the use of HTML intrinsic controls, and then we'll create another page that uses ActiveX custom controls. We'll also have a chance to see how both event and non-event code are created and used.

Creating Your First VBS-Enabled Page

In this example, we'll use the Button and Text HTML intrinsic controls. We'll also take a sneak peek at the underlying IE (Internet Explorer) object architecture, which provides access to and control of many of the built-in features of the IE.

The first example is only slightly more ambitious than a "Hello World" first effort; it uses a few lines of HTML and a short script to determine the current URL, and, accept input for a new one. Then, it changes to the new location when a Button control is clicked. Here's the full listing:

Listing 13.1 HTML.HTMùSimple HTML Control Example

<HTML>
<TITLE>Here And There</TITLE>
<p>
<INPUT TYPE=BUTTON VALUE="Where am I?" NAME="cmdWhereAmI">
<INPUT TYPE=TEXT NAME="txtWhereAmI" size=100>
<p>
<INPUT TYPE=TEXT NAME="txtWhereAmIGoing" size=100>
<INPUT TYPE=BUTTON VALUE="Where am I going?" NAME="cmdWhereAmIGoing">
<SCRIPT LANGUAGE="VBScript">
Sub cmdWhereAmI_OnClick 'Event generated when Button is clicked
txtWhereAmI.Value = Location.href
'Load Text control with current location
End Sub 'End of event procedure
Sub cmdWhereAmIGoing_OnClick 'Event generated when Button is clicked
Location.href = txtWhereAmIGoing.Value
'Set new location, from Text control contents
End Sub 'End of event procedure
</SCRIPT>
</HTML>

Startup

This example begins with three simple HTML statements:

<HTML>

<TITLE>Here And There</TITLE>

<P>

The first line is the standard HTML openerùit tells the browser that what follows (up to the closing </HTML> at the end of the page) is HTML code. (Even though VBS Scripts are not strictly speaking HTML code, they are contained within <Script> blocks, which are HTML.)

The next line creates a Title which will be displayed in the browser's Title bar. (In Visual Basic, the corresponding element is a form's Caption property.)

The third line marks a new paragraph. This causes an empty carriage return to be inserted, to leave a little whitespace at the top of the page.

Controls

The next few statements include several <Input...> tags. The <Input...> tag does not have a closing tag; this is because the declaration information is contained within the actual tag, and no closing tag is required.

<Input...> is used to declare an HTML Intrinsic control that is used to interact with the page. The TYPE= parameter declares which control (for example, Text or Button) will be used.

Remember, this is HTML, not VB (or even VBS), so where we declare the control determines its actual physical placement on the page. If you declare it at the top of the page, it appears at the top; if you declare it in the middle, it appears in the middle. (Using the HTML Layout Page features provides a powerful mechanism for dealing with this, and once you gain proficiency with VBS, you'll probably want to use it, and the ActiveX Control Pad for most serious development.)

The first control declaration line creates a Button control, and assigns it a Name and Value.

<INPUT TYPE=BUTTON VALUE="Where am I?" NAME="cmdWhereAmI">

After we declare the TYPE= as BUTTON, we need to assign two other properties: VALUE, and NAME. VALUE is the same as the Caption property in Visual Basic. Whatever you assign as the VALUE of a Button control will appear on the button. In this case, the button will say "Where am I?"

The NAME property is identical to the Name property in Visual Basic. It assigns a name to the control. Whenever you reference a control in code, you refer to it by its NAME property.

In addition to this fairly straightforward declaration, it is possible to use more complex declarations. This is described in detail in Chapters 9, "An Introduction to Distributed Objects," and 21, "VBScript Forms, Controls, and Managing Transactions."

The next line creates a Text control, and assigns it a Name and Size.

<INPUT TYPE=TEXT NAME="txtWhereAmI" SIZE=100>

Like the Button control, the Text control has a NAME property, which is used to reference the control in code. The Text control also has a SIZE property, which is used to assign a width for the control when it's created in the browser. HTML controls use a simplified series of properties when compared to Visual Basic. If you're a VB user, you may be surprised at the lack of Height and Width properties. The height is determined automatically, and the width is expressed in the maximum number of characters you want to allow in the control. In this case, we assign 100 characters as the maximum.

Text controls also have a VALUE property, which corresponds to the Text property in a Visual Basic TextBox control. If you assign any text to the VALUE when you declare the control, it will appear in the control when the control is created in the browser. Likewise, any time you assign text or a string to the VALUE in code, it will replace any existing contents with the new text. To determine text the control contains, you read the VALUE property.

The next three lines add another <P> paragraph break (to provide some more whitespace, and, assure that the next two controls start on a new line) and two more controlsùanother Text control, and another Button control.

At this point, the HTML part of the page is complete (with the exception, of course, of the closing </HTML> tag at the very end of the page). If you placed the </HTML> tag after the control declarations, you'd see the page in all its glory, just as it will appear after you add the Script to enable it. However, it will be brain-dead; you'll be able to type in the Text controls, and click the Buttons, but since there is no code to deal with those properties and events, nothing will happen. The next section details the simple script that enables this sample to actually do something.

Code

The actual script is contained in a block of matching HTML tags. The <SCRIPT LANGUAGE="VBScript"> tag marks the beginning of the script, and the </SCRIPT> closes it. Everything between these tags is VB, not HTML.

Listing 13.2 HTML.HTMùEvent Code for HTML Control Example

<SCRIPT LANGUAGE="VBScript">
Sub cmdWhereAmI_OnClick 'Event generated when Button is clicked
txtWhereAmI.Value = Location.href
'Load Text control with current location
End Sub 'End of event procedure
Sub cmdWhereAmIGoing OnClick 'Event generated when Button is clicked
Location.href = txtWhereAmIGoing.Value
'Set new location, from Text control contents
End Sub 'End of event procedure
</SCRIPT>

The code in Listing 13.2 contains two event procedures. The cmdWhereAmI OnClick Sub procedure is automatically executed when the button named cmdWhereAmI is clicked by the user. (Similar behavior rules apply to the cmdWhereAmIGoing_OnClick procedure.)

The first procedure sets the Value property of the txtWhereAmI Text control to the current value of the href property of the Location object. This results in the Text control displaying the URL for the current page.

The second procedure changes Location.href to the contents of txtWhereAmIGoing.Value, which causes the browser to load the page at the URL contained in the Text control.

To try out the example, load the CD that accompanies this book, and navigate to the icon for HTML.HTM, then double-click it. (You will need Internet Explorer 3.0 or higher installed on your machine; if you haven't already installed it, do so before trying any of the examples in this book.)

Figure 13.1 shows what you'll see when you run the program contained in Listing 13.2, and click the button captioned "Where Am I?"

FIG. 13.1

Here and There (HTML.HTM)

Using ActiveX Controls

From an implementation perspective, the same general rules that apply to HTML controls apply to ActiveX controls. The main difference is declaration style. ActiveX controls are more powerful and flexible than intrinsic HTML controls, and, their declaration is more complex too.

In the ActiveX control example that follows next in this chapter, you'll use two controlsùa Timer, and a Label. At the time this book went to press, the Internet Explorer 3.0, as well as development tools such as the ActiveX Control Pad were still in pre-release form. It's likely that you'll have these controls automatically installed by either of them, or, you can get them from the ActiveX Gallery, at:

You'll also find several other useful ActiveX controls available at that URL.

Using the Timer Control

The inTimer (Internet Explorer Timer) control is similar to the standard Timer control that is used in VB. It provides an Interval property, and has a Timer event. The setting in the Interval property tells the Timer how often to fire its Timer event. You enter the number of milliseconds you want to time, and when that time has elapsed, the Timer event occurs. (If you enter 1000, the event will fire once every second.)

If you set the Interval to 0, the event will never occur. (The Timer control also has an Enabled property. If you set it to False, it will have the same effect as setting the Interval to 0.)

Using the IeLabel Control

The IeLabel (Internet Explorer Label) control is similar to the standard Label control that is used in VB. There are two principal differences: first, the IeLabel control is an ActiveX control (rather than a built-in control, as is the case in VB). Second, the IeLabel control can be set to display its text at any angle (for example, it can display text diagonally, vertically, upside down, or anywhere in between), whereas the VB label control can only display its caption at 0 degreesùhorizontal. It is important to note that the IeLabel control itself does not change angleùit is only the text within the control that is rotatable. Therefore, the control needs to be set to a sufficient height to contain the full length of the text it contains, at whatever angle is used.

The display angle is set with the Angle property. 0 degrees results in standard, horizontal display of text, the same as a standard label control. The control's display moves counter-clockwise according to the value placed in the Angle property. So a setting of 90 degrees causes the text to run vertically, starting at the bottom.

Figure 13.2 shows the Angle property setting in the ActiveX Control Pad (described in Chapters 3-5). In this figure, the Angle property is set to 45, and the control can be seen to have its text display set to a 45 degree angle.

FIG. 13.2

Setting the Angle Property

The IeLabel control has several other properties, including:

Property Description
Caption Text that is displayed in the control
FontName Name of font used to display text
Alignment Aligns text within the control
Height Height of the control in pixels
Width Width of the control in pixels
ID Name by which you refer to the control in code (same as Name property in VB)

Creating Your First ActiveX Page

This example demonstrates the basic elements required in a VBS-enabled Web page using ActiveX controls. You'll create a page that contains the Timer and Label controls, and uses event and non-event procedures.

The complete source for the ActiveX example appears in Listing 13.3, and is contained on the CD accompanying this book in the ACTIVEX.HTM file.

Listing 13.3 ACTIVEX.HTMùThe Complete ActiveX Example

<HTML>
<HEAD>
<Center><h2>ActiveX Controls Example</h2><Center>
<SCRIPT LANGUAGE="VBScript">
Dim Direction
sub lblRotate_Click
PrepareRotation "Wheee!" 'call procedure that gets it started
end sub
Sub tmrTimer_Timer
If Direction then
lblRotate.Angle=lblRotate.Angle-10
Else
lblRotate.Angle=lblRotate.Angle+10
End If
If lblRotate.Angle=0 then 'when horizontal, left to right
tmrTimer.Interval=0 'shut off timer
lblRotate.Caption="Click Me!" 'restore label
End If
End Sub
Sub PrepareRotation (CaptionText)
lblRotate.Caption=CaptionText 'set label
Direction=Not Direction 'reverse direction
tmrTimer.Interval=18 'start timer
End Sub
</SCRIPT>
</HEAD>
<P>
<BODY>
<Center>
-----|
<OBJECT ID="lblRotate" WIDTH=151 HEIGHT=151 ALIGN=CENTER
CLASSID="CLSID:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"
CODEBASE="ielabel.ocx">
<PARAM NAME="Caption" VALUE="Click Me!">
<PARAM NAME="Angle" VALUE="0">
<PARAM NAME="ForeColor" VALUE="#000000">
<PARAM NAME="FontSize" VALUE="24">
<PARAM NAME="FontBold" VALUE="1">
</OBJECT>
|-----
</Center>
<OBJECT ID="tmrTimer" WIDTH=60 HEIGHT=49
CLASSID="CLSID:59CCB4A0-727D-11CF-AC36-00AA00A47DD2"
CODEBASE="inTimer.ocx"> </OBJECT>
</BODY>
</HTML>

As with the previous example in this chapter (HTML.HTM, under "Creating Your First VBS-Enabled Page"), this example begins with a standard <HTML> tag. This time, however, we're including a <Head> tag, so as to better conform with coding standards, which suggest placing all scripts in the <Head> section of the page, and all displayed elements in the <Body> section. Note that for modern browsers, these conventions will have no effect on display or execution of scripts. Still, HTML is far from a readable language, looking in its raw form more like ancient GWBASIC code than a modern programming language like Visual Basic, so, anything that enhances your ability to understand code after it's been written should be utilized. And, segregating VBScript code from the page proper is a good first step.

Here are the first three lines of the example:

<HTML>

<HEAD>

<Center><h2>ActiveX Controls Example</h2><Center>

The <H2> (fairly large heading) line is also placed in the <Head> section as per standard practice. (See Chapter 2, "Review of HTML," and Appendix B, "HTML Reference," for more on HTML.)

Having said all this, we're now going to (apparently) break with this pattern, and examine the example in a seemingly random pattern. There is a method to the madness, however; it's called HTML. It's because of the vagaries of HTML, which require declarations to be placed as a hodgepodge scattered throughout the document, that we have to examine it this way. (Scripts are placed ahead of content, and controls are embedded in content. Before you can understand scripts, you need to understand controls.)

Designing the Layout

After creating the HTML skeleton, the first stage in creating a page is layout design. Remember, we're not in VB anymore, so it's not a simple process of dragging controls around on a form. All positioning is determined by placement in the text (and to a lesser degree by factors such as <Center> tags and Align attributes), and size is determined by setting properties in HTML code. (Of course, when you're using HTML Layout Pagesùdiscussed in Chapters 3-5ùyou are free of HTML limitations, and you can work in a manner nearly identical to VB.)

Declaring the Controls

Declaration of ActiveX controls is handled differently from declaration of HTML intrinsic controls. However, they are still declared using HTML tags; they are not declared inside of VBS scripts. And, unless you're using the ActiveX Control Pad to create HTML Layout Pages, they are also subject to the rules concerning positioning on the page: where they are declared in code determines where they appear when the page is displayed.

Here's the first declaration encountered in the ACTIVEX.HTM example. It creates an instance of the IeLabel (Internet Explorer Label) control:

<OBJECT ID="lblRotate" WIDTH=151 HEIGHT=151 ALIGN=CENTER

CLASSID="CLSID:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"

CODEBASE="ielabel.ocx">

<PARAM NAME="Caption" VALUE="Click Me!">

<PARAM NAME="ForeColor" VALUE="#000000">

<PARAM NAME="FontSize" VALUE="24">

<PARAM NAME="FontBold" VALUE="1">

</OBJECT>

The IeLabel control is used to place text on an HTML form. It also accepts mouse events, and, can display its output at any angle.

The first thing you may notice in this section of the example is the <Object...> open-ended tag. HTML intrinsic controls are declared with the <Input...> open-ended tag, followed by their type, and other HTML properties. ActiveX controls, on the other hand, are declared as Objects, and require additional information. The IeLabel control declared here contains a mix of HTML and ActiveX properties.

HTML properties are defined with a simple assignment statement. The property name is to the left of an equal sign, and the value is on the right. It is important to place them inside the opening <Object...> tag. Note the > after the align=center assignment. The HTML part of the declaration, including setting of HTML properties, takes place within the opening <Object...> tag itself. The ActiveX properties are placed after the <Object...>, but before the </Object> closing tag (see Table 13.1). Confused yet? Here's the format:

Because this declaration is all HTML code, it can be placed on a single line or broken into multiple lines at your discretion.

The HTML part of the declaration contains entries for CODEBASE, CLASSID, ID, WIDTH, HEIGHT, and ALIGN properties. Other controls (or this control in other applications) require additional properties, however, the ones used here are fairly universal.

Table 13.1 ActiveX Properties

Part Description
CODEBASE="IeLabel.ocx" Points to the filename of the .OCX containing this control (This info is buried deep in your Windows Registry, and can be retrieved, and pasted into an HTML or HTML Layout Page document with the ActiveX Control Pad (described in Chapters 3-5). This property is also used to point to a URL containing a control that can be automatically downloaded to the user's machine. See "Using Objects in HTML Pages," in Chapter 12, "Designing VBScript Applications."
CLASSID="CLSID:99...D2" Must point to this control's ClassID in the Registryùthe ClassID can be retrieved, and pasted into an HTML or HTML Layout Page document with the ActiveX Control Pad (described in Chapters 3-5).
ID=lblRotate The name you'll use for this control in your scripts
WIDTH=100 This control's width in pixels in the browser
HEIGHT=100 This control's height in pixels in the browser
ALIGN=CENTER This control's alignment on the text line in the browser

The other thing you've probably noticed is that the ActiveX property assignments are a bit more complex then their HTML counterparts. The <Param...> tag is used to hold all information for a single declaration. This tag is similar to the <Object...> tag in that it contains declaration information within the tag, but it is different in that it has no counterpart to the </Object> tag.

The assignment is in the format name="PropertyName" value="PropertyContents". Note that the property name must be delimited by quotation marks.

The timer control (InTimer), is declared similarly to the the label control; being a different type of control, it uses different properties, but the format is the same, as it is for all ActiveX controls. Here's the relevant section of ACTIVEX.HTM:

<OBJECT ID="tmrTimer" WIDTH=0 HEIGHT=0

CLASSID="CLSID:59CCB4A0-727D-11CF-AC36-00AA00A47DD2"

CODEBASE="inTimer.ocx"> </OBJECT>

This declaration only contains HTML property assignments. We set its ActiveX Interval property in VBS code in the "Writing Event Handlers" section of this chapter. We set its Width and Height to 0, since it's an invisible control, and we don't want it to consume any more HTML space than necessary.

Script Block Declaration

<SCRIPT LANGUAGE="VBScript">

Dim Direction

Here, we declare the beginning of our Script block. We also create a script-level variable with the Dim Direction statement. This variable is available to all procedures in our script. (Scoping issues are discussed in the next section of this chapter, "Writing Event Handlers".)

Writing Event Handlers

Event handlers are contained inside a <Script> block. (Event handlers are Sub procedures that automatically execute whenever the specified event occurs. They are covered more extensively in Chapter 19, "VBScript Event Programming.")

The first event handler in the script deals with the Click event of the Label control. Because the ID of the control was set to lblRotate, the event handler Sub procedure is named lblRotate_Click. (Event handlers begin with the name of the control, and use an underscore to attach it to the name of the event.) This is the actual event code from ACTIVEX.HTM:

sub lblRotate_Click

PrepareRotation "Wheee!" 'call procedure that gets it started

end sub

This procedure contains the Click event for the lblRotate control. In this case, we simply use it to call the PrepareRotation non-event procedure, which is discussed later on in this section. This code executes when you click on the label control, and starts the process that makes the label rotate on screen.

Here's the code that executes after it's called by the click event:

Sub PrepareRotation (CaptionText)

lblRotate.Caption=CaptionText 'set label

Direction=Not Direction 'reverse direction

tmrTimer.Interval=18 'start timer

End Sub

The PrepareRotation Sub is called from the lblRotate Click event, which also passes it the CaptionText parameter. Although the call that invokes this routine passes a string literal (text contained in quotation marks), here it is converted to the CaptionText variable, because it's declared as a parameter in the Sub declaration.

This routine also uses the Direction variable, which is available because it was declared at the Script level, rather than declared inside another procedure. (A variable's scope is generally determined by where it is declared. If it is declared inside a script, but outside any procedure in that script, it is available to all procedures in all scripts. If it is declared inside a procedure, it only exists within that procedure.)

This is the place where we set the timer control's Interval property, which tells the control to begin its countdown to firing its Time event. We have set it to 18 milliseconds. (When it is set to 0, which is its default, the event never fires.)

Next, the event handler for the Time event of the Timer control (IeTimer) is added. Here's the complete event routine:

Sub tmrTimer_Timer

If Direction then

lblRotate.Angle=lblRotate.Angle-10

Else

lblRotate.Angle=lblRotate.Angle+10

End If

If lblRotate.Angle=0 then 'when horizontal, left to right

tmrTimer.Interval=0 'shut off timer

lblRotate.Caption="Click Me!" 'restore label

End If

End Sub

The tmrTimer event procedure fires each time the interval assigned to the timer control's Interval property transpires. The code in this event procedure does a fair amount of work. It contains two If/Then blocks (described in Chapter 18, "VBScript Control of Flow and Error Handling"). The first one tests for the direction of rotation. If it's True, it decreases the value of the Angle property of the label control by ten degrees; otherwise, it increases it by ten degrees:

If Direction then

lblRotate.Angle=lblRotate.Angle-10

Else

lblRotate.Angle=lblRotate.Angle+10

End If

The second If/Then block determines when to stop moving:

If lblRotate.Angle=0 then 'when horizontal, left to right

tmrTimer.Interval=0 'shut off timer

lblRotate.Caption="Click Me!" 'restore label

End If

When the Angle property of the label control equal 0 (indicating that the text is at a horizontal, left-to-right orientation), it shuts off the timer by setting its Timer property to 0, and, restores the label's caption to its original contents.

Listing 13.4 contains the complete ActiveX example page. Locate the ACTIVEX.HTM example on the CD, then double-click its icon to load it into your browser. You'll see a label captioned "Click Me!" When you click the label, its caption changes, and it begins to rotate in a clockwise direction. When it has completed 360 degrees, it stops, and its caption is restored. If you click it again, it rotates again in the opposite direction. If you click it while it is rotating, it immediately reverses direction.

Here's how it will look after you load it (see fig. 13.3):

FIG. 13.3

ACTIVEX.HTM Example

And here's how it will appear right after you click the label (see fig. 13.4):

FIG. 13.4

ACTIVEX.HTM Example, in Motion

While this demonstration doesn't accomplish any real work, it does demonstrate how just a few lines of VBS code, combined with a couple of control declarations, and a handful of HTML code, can automate a Web page.

We've placed the VBS script code in the <Head> block, although it will work fine in the <Body> too. By placing it all in the <Head> section, we free up the <Body> for control declarations (remember, where we declare them determines where they appear), and text. This makes formatting the actual page much simpler, as the HTML source will more closely resemble the final output in the browser.

Testing the Page

Before a page is published it needs to be tested. You'll probably want to do most of your initial testing locally (rather than over the Internet, or on your Intranet server) unless you have a high-speed network connection and tools to make upload relatively transparent.

Local Testing

Local testing is fairly painless, since it essentially consists of saving the HTML file with your text editor, then either double-clicking its icon, or clicking the Reload button in your browser (if it's currently loaded from a previous test). There are a few caveats, however. If your page includes links to other pages or files, you have to make sure that the links are either absolute links (fully qualified URLs), or, if relative links, are duplicated on both systems (your local machine and the remote host on which the page will ultimately reside) in the exact same structure.

Relative links are links that point to a file in a directory that is relative to the current URL. Absolute links point to a complete URL.

This is a relative link:

<A HREF="/pages/page1.htm"><B>First Page</A></B>

And this is an absolute link:

<A HREF="http://www.nethawk.com/~rs><B>Home Page</A></B>

Note that the relative link doesn't include a host nameùit only includes a path, and file name.

Relative links are generally preferred because it is easier to port a page from one machine or path to another, but you must make sure to port all files that are referenced, and keep them in the same path relative to the original. If you keep all related files in the same directory as your page, you're setùjust copy them all together. If you include them in a tree inside your working directory, it's fairly trivial to duplicate the tree on the target machine. If, however, you are referencing lateral branches and facing the task of duplicating massive and/or complex directory structures on other machines, you may want to consider editing your page to use a more concise structure.

As with most programming issues, there are tradeoffs, and no two situations are exactly alike. If you are aware of the considerations from the outset, you can craft your pages in such a way as to minimize porting headaches later on.

Remote Testing

Unless you are developing your pages on the same machine that will serve as their HTTP server, you need to transfer them before they can be accessed by Internet or Intranet users. As flawlessly as they may perform after extensive local testing, you still need to run them through their paces after you place them on the server. Subtle errors, usually related to link names, frequently fail to be detected during local testing.

From Here...

For more information on HTML programming, check out A Beginner's Guide to HTML, at the following URL:

Also, check out these other chapters for additional information:


| Previous Chapter | Next Chapter |

| Search | Table of Contents | Book Home Page | Buy This Book |

| Que Home Page | Digital Bookshelf | Disclaimer |


To order books from QUE, call us at 800-716-0044 or 317-361-5400.

For comments or technical support for our books and software, select Talk to Us.

© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.